import {userProfile} from "../../entity/UserProfile";
import Common from "../../../framework/utils/Common";

// @ts-ignore
const wx = window.wx;

if (wx) {
    try {
// @ts-ignore
        require("./ald-game");
    } catch (e) {
        cc.log("未集成ald-game sdk");
    }
}

class Logger {

    // 当前统计关卡.
    private readonly currentStage: { stageId: string, stageName: string, userId?: string } = {stageId: "", stageName: ""};

    public setup() {
        if (wx && wx.aldStage) {
            cc.log("阿拉丁初始化成功.")
        } else {
            cc.log("阿拉丁初始化失败.")
        }
    }

    public sendEvent(key: string, value?: object) {
        if (value && typeof value === "object") {
            value["uid"] = userProfile.userId;
        }
        if (!value) {
            value = {uid: userProfile.userId}
        }
        if (wx && wx.aldSendEvent) {
            wx.aldSendEvent(key, value);
        } else {
            cc.log("==统计:", key, value);
        }
    }

    public onShareAppMessage(callback: Function) {
        if (wx && wx.aldOnShareAppMessage) {
            wx.aldOnShareAppMessage(callback);
        } else if (wx) {
            wx.onShareAppMessage(callback);
        }
    }

    /**
     * 分享接口.
     * @param data
     * @param descr 分享用途的描述.
     */
    public shareAppMessage(data: any, descr?: string) {
        if (wx && wx.aldShareAppMessage) {
            data["ald_desc"] = descr ? descr : "通用";
            wx.aldShareAppMessage(data);
        } else if (wx) {
            wx.shareAppMessage(data);
        }
    }

    public onGameStart(stageId: string, stageName: string, userId?: string) {
        Common.assign(this.currentStage, {stageId, stageName, userId: userId || userProfile.userId})
        if (wx && wx.aldStage) {
            wx.aldStage.onStart(this.currentStage);
        } else {
            cc.log("==统计:", "onStart", this.currentStage);
        }
    }

    public onGameRunning(event: string, params: { itemName: string, itemId?: string, itemCount?: number, desc?: string, itemMoney?: number }) {
        if (wx && wx.aldStage) {
            wx.aldStage.onRunning(Common.deepAssign({}, this.currentStage, {event, params}));
        } else {
            cc.log("==统计:", "onRunning", this.currentStage, event, params);
        }
    }

    public onGameEnd(event: string, params?: { desc: string; }) {
        if (wx && wx.aldStage) {
            wx.aldStage.onEnd(Common.deepAssign({}, this.currentStage, {event, params}));
        } else {
            cc.log("==统计:", "onEnd", this.currentStage, event, params);
        }
    }
}

export const logger: Logger = new Logger();